package com.pxxy.lawconsult.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pxxy.lawconsult.bean.Case;
import com.pxxy.lawconsult.constant.DBConstant;
import com.pxxy.lawconsult.utils.DBUtils;

@WebServlet("/GetCaseServlet")
public class GetCaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String REQUEST_CASETYPE = "requestCaseType";
	private static final String REQUEST_CASETYPE_REFRESH = "refresh";
	private static final String REQUEST_CASETYPE_LOADING = "loading";
	public static List<Case> caseList = null;
	public Gson gson = null;

	public GetCaseServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String start = request.getParameter("start");
		response.setCharacterEncoding("UTF-8");
		gson = new Gson();
		PrintWriter out = response.getWriter();
		//获取数据，定时更新
		int time = 60*60*1000;
		getAllCase(time);
		//获取数据
		List<Case> resultCase = new ArrayList<>();
		int startCase = Integer.parseInt("start");
		int caseCount = caseList.size()-startCase;
		int maxCase = 0;
		if(caseCount>=5) {
			maxCase = 5;
		}else {
			maxCase = caseCount;
		}
		
		for(int i=0;i<maxCase;i++) {
			resultCase.add(caseList.get(startCase++));
		}
		
		String json = gson.toJson(resultCase);
		
		for(Case mCase:resultCase) {
			System.out.println(mCase.getContent());
		}
		
		out.println(json);
	}

	public void getAllCase(int time) {
		Timer timer = new Timer(true);
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				try {
					caseList = new ArrayList<>();
					ResultSet rs = DBUtils.query(DBConstant.TB_CASE_TABLE, null, null);
					while (rs.next()) {
						Case myCase = new Case();
						myCase.setId(rs.getInt(DBConstant.CASE_TABLE_CASE_ID));
						myCase.setTitle(rs.getString(DBConstant.CASE_TABLE_CASE_TITLE));
						myCase.setContent(rs.getString(DBConstant.CASE_TABLE_CASE_CONTENT));
						myCase.setImage(rs.getString(DBConstant.CASE_TABLE_CASE_IMAGE));
						myCase.setType(rs.getString(DBConstant.CASE_TABLE_CASE_TYPE));

						caseList.add(myCase);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 0, time);

	}

}
